package tables

import (
	"fmt"
	template2 "html/template"

	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
	"github.com/GoAdminGroup/go-admin/template"
	"github.com/GoAdminGroup/go-admin/template/types"
	"github.com/GoAdminGroup/go-admin/template/types/form"
	editType "github.com/GoAdminGroup/go-admin/template/types/table"
)

func GetAycontentsortTable(ctx *context.Context) table.Table {

	ayContentSort := table.NewDefaultTable(ctx, table.DefaultConfigWithDriverAndConnection("sqlite", "pbootcms"))
	tblName := "ay_content_sort"
	info := ayContentSort.GetInfo()
	// 	mp, _ := db.CommonQuery(conn.GetDB("pbootcms"),
	// 		strings.ReplaceAll(`WITH RECURSIVE cte AS (
	//     SELECT scode, name, 1 depth, name as path FROM tblName WHERE pcode="0"
	//     UNION ALL SELECT tblName.scode, tblName.name, depth+1,path || '->' || tblName.name as path
	//     FROM cte inner JOIN tblName ON cte.scode = tblName.pcode
	// ) SELECT * FROM cte;
	// `, "tblName", "ay_content_sort"))
	// 	fmt.Printf("\n\n%+v\n\n", mp)

	info.AddField("Id", "id", db.Integer).FieldSortable()
	info.AddField("分类名称", "name", db.Text).FieldEditAble(editType.Text)
	info.AddField("分类编码", "scode", db.Text).FieldEditAble(editType.Text)
	info.AddField("内容模型编码", "mcode", db.Text).
		FieldDisplay(func(value types.FieldModel) any {
			return template.Default().Link().
				SetURL("/admin/info/ay_model/detail?__goadmin_detail_pk=" + value.Value).
				SetContent(template.HTML(value.Value)).OpenInNewTab().
				SetTabTitle(template.HTML("模型详情(" + value.Value + ")")).
				GetContent()
		})

	info.AddField("模型名称", "name1", db.Varchar).
		FieldDisplay(func(value types.FieldModel) any {
			name, _ := value.Row["ay_model_goadmin_join_name"].(string)
			// return name
			return template.Default().Link().
				SetURL("/admin/info/ay_model/detail?__goadmin_detail_pk=" + value.Row["mcode"].(string)).
				SetContent(template.HTML(name)).OpenInNewTab().
				SetTabTitle(template.HTML("模型详情(" + name + ")")).
				GetContent()
		})
	info.AddField("modelname", "name", db.Varchar).FieldJoin(types.Join{
		Field:     "mcode",
		JoinField: "id",
		Table:     "ay_model",
	}).FieldHide()

	info.AddField("父编码", "pcode", db.Text).FieldEditAble()
	info.AddField("列表页模板", "listtpl", db.Text)
	info.AddField("内容页模板", "contenttpl", db.Text)
	info.AddField("状态", "status", db.Text).FieldDisplay(filter01("隐藏", "显示")).
		FieldEditAble(editType.Switch).FieldEditOptions(opt01("隐藏", "显示"))
	info.AddField("区域编码", "acode", db.Text)
	info.AddField("转外链接", "outlink", db.Text).FieldHide()
	info.AddField("附加名称", "subname", db.Text)
	info.AddField("分类缩略图", "ico", db.Text).FieldHide()
	info.AddField("分类大图", "pic", db.Text).FieldHide()
	info.AddField("seo标题", "title", db.Text).FieldHide()
	info.AddField("分类关键字", "keywords", db.Text).FieldEditAble()
	info.AddField("分类描述", "description", db.Text).FieldEditAble()
	info.AddField("自定义文件名", "filename", db.Text)
	info.AddField("排序", "sorting", db.Integer)
	info.AddField("创建人员", "create_user", db.Text).FieldHide()
	info.AddField("更新人员", "update_user", db.Text).FieldHide()
	info.AddField("创建时间", "create_time", db.Text).FieldHide()
	info.AddField("更新时间", "update_time", db.Text).FieldHide()
	info.AddField("Gtype", "gtype", db.Text)
	info.AddField("Gid", "gid", db.Text).FieldHide()
	info.AddField("Gnote", "gnote", db.Text).FieldHide()
	info.AddField("栏目描述1", "def1", db.Text).FieldHide()
	info.AddField("栏目描述2", "def2", db.Text).FieldHide()
	info.AddField("栏目描述3", "def3", db.Text).FieldHide()

	// 统计各模型下有多少分类
	results, _ := db.WithDriverAndConnection("pbootcms", conn).
		Table(tblName).Select("mcode", "count(mcode)").GroupBy("mcode").All()

	/*
		map[count(`mcode`):3 mcode:1]
		map[count(`mcode`):3 mcode:2]
		map[count(`mcode`):3 mcode:3]
		map[count(`mcode`):1 mcode:4]
		map[count(`mcode`):1 mcode:5]
	*/

	mcodes, _ := db.WithDriverAndConnection("pbootcms", conn).
		Table("ay_model").Select("mcode", "name").All()
	/*
		map[mcode:1 name:专题]
		map[mcode:2 name:新闻]
		map[mcode:3 name:产品]
		map[mcode:4 name:案例]
		map[mcode:5 name:招聘]
		map[mcode:6 name:总结1]
	*/
	// for _, v := range mcodes {
	// 	fmt.Printf("%+v", v)
	// 	println()
	// }

	heads := make(types.Thead, len(results))
	infoItems := make(map[string]types.InfoItem, len(results))
	for i, v := range results {
		name := fmt.Sprint(mcodes[i]["name"])
		v1 := fmt.Sprint(v["count(`mcode`)"])
		heads[i] = types.TheadItem{Head: name}
		infoItems[name] = types.InfoItem{Content: template2.HTML(v1)}
	}

	info.SetWrapper(func(content template2.HTML) template2.HTML {
		tableContent := template.Default().Table().SetThead(heads).
			SetInfoList([]map[string]types.InfoItem{infoItems}).GetContent()
		return template.Default().Box().
			SetBody(tableContent).
			SetNoPadding().
			WithHeadBorder().
			GetContent() + content
	})
	info.SetTable(tblName).SetTitle("文章分类").SetDescription("文章分类")

	formList := ayContentSort.GetForm()
	formList.AddField("Id", "id", db.Integer, form.Default).FieldDisplayButCanNotEditWhenUpdate().FieldNotAllowAdd()
	formList.AddField("区域编码", "acode", db.Text, form.SelectSingle).FieldOptions(types.FieldOptions{
		{Text: "cn", Value: "0"},
		{Text: "en", Value: "1"},
	}).FieldDefault("0")
	formList.AddField("内容模型编码", "mcode", db.Text, form.SelectSingle).
		FieldOptionsFromTable("ay_model", "name", "mcode")
	formList.AddField("父编码", "pcode", db.Text, form.SelectSingle).
		FieldOptionsFromTable(tblName, "name", "scode")
	formList.AddField("分类编码", "scode", db.Text, form.Number)
	formList.AddField("分类名称", "name", db.Text, form.Text)
	formList.AddField("列表页模板", "listtpl", db.Text, form.Text)
	formList.AddField("内容页模板", "contenttpl", db.Text, form.Text)
	formList.AddField("状态", "status", db.Text, form.Radio).
		FieldOptions(opt01("隐藏", "显示")).FieldDefault("1")
	formList.AddField("转外链接", "outlink", db.Text, form.Text)
	formList.AddField("附加名称", "subname", db.Text, form.Text)
	formList.AddField("分类缩略图", "ico", db.Text, form.Text)
	formList.AddField("分类大图", "pic", db.Text, form.Text)
	formList.AddField("seo标题", "title", db.Text, form.Text)
	formList.AddField("分类关键字", "keywords", db.Text, form.Text)
	formList.AddField("分类描述", "description", db.Text, form.Text)
	formList.AddField("自定义文件名", "filename", db.Text, form.Text)
	formList.AddField("排序", "sorting", db.Integer, form.Number).
		FieldDefault("255")
	formList.AddField("创建人员", "create_user", db.Text, form.Text).FieldDefault("admin")
	formList.AddField("更新人员", "update_user", db.Text, form.Text).FieldDefault("admin")
	formList.AddField("创建时间", "create_time", db.Text, form.Datetime).FieldNowWhenInsert()
	formList.AddField("更新时间", "update_time", db.Text, form.Datetime).FieldNowWhenUpdate()
	formList.AddField("Gtype", "gtype", db.Text, form.Text).
		FieldDefault("4")
	formList.AddField("Gid", "gid", db.Text, form.Text)
	formList.AddField("Gnote", "gnote", db.Text, form.Text)
	formList.AddField("栏目描述1", "def1", db.Text, form.Text)
	formList.AddField("栏目描述2", "def2", db.Text, form.Text)
	formList.AddField("栏目描述3", "def3", db.Text, form.Text)

	ayContentSort.GetForm().SetTabGroups(types.
		NewTabGroups("id", "acode", "mcode", "pcode", "scode", "name",
			"listtpl", "contenttpl", "status").
		AddGroup("outlink", "subname", "ico", "pic", "title", "keywords", "description", "filename", "sorting", "gtype", "gid", "gnote", "def1", "def2", "def3",
			"create_user", "update_user", "create_time", "update_time")).
		SetTabHeaders("基本信息", "更多信息")
	formList.SetTable(tblName).SetTitle("编辑文章分类").SetDescription("编辑文章分类")

	return ayContentSort
}
